//账号安全
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:hxdj/common/base_page/my_loading_page.dart';
import 'package:hxdj/common/components/my_alert.dart';
import 'package:hxdj/common/components/my_clip_rect.dart';
import 'package:hxdj/common/components/my_smart_refresher.dart';
import 'package:hxdj/common/components/my_tap_widget.dart';
import 'package:hxdj/common/my_common.dart';
import 'package:hxdj/common/my_get_it.dart';
import 'package:hxdj/common/my_global.dart';
import 'package:hxdj/common/my_header_global.dart';
import 'package:hxdj/common/routers/navigator.dart';
import 'package:hxdj/message/message_page/message_viewmodel.dart';
import 'package:hxdj/message/rongcloud/chat/rc_chat_global_viewmodel.dart';
import 'package:hxdj/message/rongcloud/rc_chat/rc_chat_page.dart';
import 'package:hxdj/message/sys_message/sys_message_page.dart';
import 'package:provider/provider.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:sticky_headers/sticky_headers.dart';

//消息中心
class MessagePage extends StatefulWidget {
  static String routeName = "/MessagePage";

  const MessagePage({super.key});

  @override
  State<MessagePage> createState() => _MessagePageState();
}

class _MessagePageState extends State<MessagePage> with SingleTickerProviderStateMixin {
  //viewModel
  MessageViewModel? viewModel;

  late ScrollController crollController = ScrollController();

  late RefreshController refreshController = RefreshController();

  late SlidableController slidableController = SlidableController(this);

  @override
  void initState() {
    super.initState();

    WidgetsBinding.instance.addPostFrameCallback((_) {
      viewModel = Provider.of<MessageViewModel>(context, listen: false);
      viewModel!.context = context;
      //登录IM
      viewModel!.loginIM();
    });
  }

  _buildBody() {
    switch (viewModel?.state) {
      case ViewState.loading:
        return const MyLoadingWidget();
      case ViewState.empty:
        return Center(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              MyImage(imageName: "ic_message_nodate", width: 150.w, height: 150.w),
              Container(
                padding: EdgeInsets.only(top: 25.h),
                child: RichText(
                    text: TextSpan(
                        style: TextStyle(color: MyColours.colorA2A2A2, fontSize: 12.sp, height: 1.2),
                        children: [
                      const TextSpan(text: '您还没有消息哦，去'),
                      TextSpan(
                          recognizer: TapGestureRecognizer()
                            ..onTap = () {
                              debugPrint("点击了下单");
                              
                               MyGlobalViewModel globalViewModel = MyGlobalViewModel.getGlobalViewModel(context);
                              globalViewModel.setIndex(1);
                            },
                          text: '下单',
                          style: const TextStyle(color: MyColours.appMain)),
                      const TextSpan(text: '试试吧～'),
                    ])),
              ),
            ],
          ),
        );
      case ViewState.normal:
        return MySmartRefresher(
            enablePullUp: false,
            enablePullDown: true,
            customChildWidget: ListView.builder(
                itemCount: viewModel?.dataList.keys.length,
                itemBuilder: (context, index) {
                  List<String> keys = viewModel!.dataList.keys.toList();

                  Map<String, dynamic> dataMap = viewModel?.dataList[keys[index]];
                  //
                  return StickyHeader(
                      header: Container(
                        height: 40.h,
                        color: MyColours.bgColor,
                        padding: EdgeInsets.symmetric(horizontal: 16.0.w),
                        alignment: Alignment.centerLeft,
                        child: Text(
                          keys[index],
                          style: MyTextStyles.textBlackBold16,
                        ),
                      ),
                      content: dataMap['type'] == 'sys'
                          ? Column(children: _buildSysMessage(dataMap['group']))
                          : _buildMessage(dataMap['group']));
                }),
            onRefresh: () async {
              await Future.delayed(const Duration(milliseconds: 500));
              viewModel?.requetsData();
            },
            scrollController: crollController,
            controller: refreshController);
      default:
        return Container();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<MessageViewModel>(builder: (context, model, child) {
      //刷新完成
      refreshController.refreshToIdle();

      return Scaffold(
          backgroundColor: MyColours.bgColor,
          appBar: MyAppBar(
            title: "消息中心",
            actionImageName: viewModel?.state == ViewState.normal ? "ic_clean_message" : "",
            isBack: false,
            onPressed: () {
              debugPrint("点击了清除按钮");

              viewModel?.cleanAllUnreadMessage();
            },
          ),
          body: _buildBody());
    });
  }

//系统消息
  _buildSysMessage(List<SysMessageModel> group) {
    return group.map((SysMessageModel item) {
      return Container(
        color: MyColours.bgColor,
        child: GestureDetector(
          onTap: () {
            //获取系统消息
            NavigatorUtils.pushParams(context, "${SysMessagePage.routeName}?messageId=1231");
          },
          child: Container(
            decoration: BoxDecoration(
              color: MyColours.materialBg,
              //设置四周圆角 角度
              borderRadius: BorderRadius.circular(15.w),
              boxShadow: [
                BoxShadow(
                  blurRadius: 5.w,
                  color: MyColours.color0D141B,
                  //向右下偏移的距离
                  offset: const Offset(0, 4),
                )
              ],
            ),
            //设置四周边框
            margin: EdgeInsets.symmetric(horizontal: 10.w, vertical: 5.h),
            alignment: Alignment.centerLeft,
            padding: EdgeInsets.only(left: 10.w, top: 17.h, bottom: 17.h, right: 15.w),
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                //头像
                Padding(
                  padding: EdgeInsets.only(right: 7.5.w),
                  child: MyClipRect(imageUrl: item.img, width: 40.w, radius: 20.w),
                ),
                //名字, 最近消息
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Padding(
                        padding: EdgeInsets.only(bottom: 5.h),
                        child: Text(item.name ?? "", style: MyTextStyles.textBlackBold16),
                      ),
                      Text(item.content ?? "", style: TextStyle(color: MyColours.color848484, fontSize: 13.sp)),
                    ],
                  ),
                ),
              ],
            ),
          ),
        ),
      );
    }).toList();
  }

  _buildMessage(List group) {
    return Container(
      color: MyColours.bgColor,
      child: Container(
          decoration: BoxDecoration(
            color: MyColours.materialBg,
            //设置四周圆角 角度
            borderRadius: BorderRadius.circular(15.w),
            boxShadow: [
              BoxShadow(
                blurRadius: 5.w,
                color: MyColours.color0D141B,
                //向右下偏移的距离
                offset: const Offset(0, 4),
              )
            ],
          ),
          //设置四周边框
          margin: EdgeInsets.symmetric(horizontal: 10.w, vertical: 5.h),
          alignment: Alignment.centerLeft,
          child: SlidableAutoCloseBehavior(
            child: ListView.separated(
              shrinkWrap: true,
              physics: const NeverScrollableScrollPhysics(),
              controller: crollController, //需要controller ,不然异常
              itemCount: group.length,
              key: Key(UniqueKey().toString()),
              itemBuilder: (BuildContext context, int index) {
                ConversationMessage conversation = group[index];

                // /// 消息携带的用户信息
                // RCIMIWUserInfo? userInfo = conversation.lastMessage?.userInfo;

                return Slidable(
                  // 禁用滑动
                  enabled: true,
                  dragStartBehavior: DragStartBehavior.start,
                  // 设置只能有一个滑块
                  key: Key(UniqueKey().toString()),

                  //左滑划出的菜单
                  endActionPane: ActionPane(
                    key: Key(UniqueKey().toString()),
                    // 菜单宽度
                    extentRatio: 0.2,
                    dragDismissible: false,
                    // 滑动动效
                    // DrawerMotion() StretchMotion()
                    // motion: ScrollMotion(),
                    motion: const BehindMotion(),
                    children: [
                      MyCustomMySlidableAction(
                        borderRadius: index == 0
                            ? BorderRadius.only(topRight: Radius.circular(15.w))
                            : (index == group.length - 1
                                ? BorderRadius.only(bottomRight: Radius.circular(15.w))
                                : const BorderRadius.all(Radius.zero)),
                        onPressed: (a) {
                          //是否删除该会话
                          MyAlertManager.showAlert(AlertType.iosMode, context, "您确定要删除吗？", "", onSure: () {
                            viewModel!.deleteConversation(conversation.targetId!, (_) {
                              group.removeAt(index);
                              setState(() {});
                            });
                          }, close: "再想想", sure: "确定");
                        },
                        flex: 1,
                        child: Text(
                          "删除",
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(color: MyColours.materialBg, fontSize: 14.sp),
                        ),
                      ),
                    ],
                  ),
                  child: MyTapWidget(
                    onTap: () {
                      //获取聊天详情
                      NavigatorUtils.pushParams(context, "${RCChatPage.routeName}?targetId=${conversation.targetId}")
                          .then((value) {
                        final RCChatGlobalModel globalModel = serviceLocator<RCChatGlobalModel>();
                        globalModel.clearUnreadCount(conversation.targetId!);

                        viewModel!.updateRecentConversationList(conversation.targetId!,isNeedAll: false);
                      });
                    },
                    child: Container(
                      alignment: Alignment.centerLeft,
                      child: Row(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          //头像
                          Stack(
                            clipBehavior: Clip.none,
                            children: [
                              Padding(
                                padding: EdgeInsets.only(left: 10.w, top: 15.h, right: 7.w, bottom: 15.h),
                                child: MyClipRect(
                                    placeholder: (p0, p1) {
                                      return MyClipRect(
                                       
                                        imageName: "ic_chat_header_default",
                                        width: 40.w,
                                        height: 40.w,
                                        radius: 8.w,
                                      );
                                    },
                                    errorWidget: (p0, p1, p2) {
                                      return MyClipRect(
                                        imageName: "ic_chat_header_default",
                                        width: 40.w,
                                        height: 40.w,
                                        radius: 8.w,
                                      );
                                    },
                                    imageUrl: conversation.headImageName ?? "",
                                    width: 40.w,
                                    height: 40.w,
                                    radius: 20.w),
                              ),
                              Positioned(
                                right: 3.w,
                                top: 15.w,
                                child: conversation.unreadCount == 0
                                    ? Container()
                                    : Container(
                                        alignment: Alignment.center,
                                        decoration: BoxDecoration(
                                          color: MyColours.colorE33432,
                                          shape: BoxShape.rectangle,
                                          borderRadius: BorderRadius.all(Radius.circular(8.w)),
                                        ),
                                        padding: EdgeInsets.only(left: 2.w, right: 3.w),
                                        constraints: BoxConstraints(
                                          minWidth: 15.w,
                                          maxHeight: 15.w,
                                          minHeight: 13.w,
                                        ),
                                        child: Text(conversation.unreadCount.toString(),
                                            textAlign: TextAlign.center,
                                            style: TextStyle(color: Colors.white, fontSize: 11.sp)),
                                      ),
                              ),
                            ],
                          ),

                          //名字, 最近消息
                          Expanded(
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Padding(
                                  padding: EdgeInsets.only(bottom: 5.h),
                                  child: Text(
                                      CommonPlugin.isEmpty(conversation.name ?? "")
                                          ? conversation.targetId!
                                          : (conversation.name ?? ""),
                                      style: MyTextStyles.textBlackBold16),
                                ),
                                Text(conversation.lateMessageContent,
                                    maxLines: 1,
                                    overflow: TextOverflow.ellipsis,
                                    style: TextStyle(color: MyColours.color848484, fontSize: 13.sp)),
                              ],
                            ),
                          ),

                          // 时间
                          Container(
                            padding: EdgeInsets.only(right: 10.w),
                            child: Text(conversation.lateMessageTime ?? "",
                                style: TextStyle(color: MyColours.colorBFBFBF, fontSize: 12.sp)),
                          ),
                        ],
                      ),
                    ),
                  ),
                );
              },
              separatorBuilder: (BuildContext context, int index) {
                return Container(
                    padding: const EdgeInsets.only(left: 60, right: 10),
                    child: const Divider(
                      height: 0,
                      color: MyColours.bgColor,
                    ));
              },
            ),
          )),
    );
  }
}

/// Signature for [MyCustomMySlidableAction.onPressed].
typedef MySlidableActionCallback = void Function(BuildContext context);

const int _kFlex = 1;
const Color _kBackgroundColor = Colors.white;
const bool _kAutoClose = true;

/// Represents an action of an [ActionPane].
class MyCustomMySlidableAction extends StatelessWidget {
  /// Creates a [MyCustomMySlidableAction].
  ///
  /// The [flex], [backgroundColor], [autoClose] and [child] arguments must not
  /// be null.
  ///
  /// The [flex] argument must also be greater than 0.
  const MyCustomMySlidableAction({
    super.key,
    this.flex = _kFlex,
    this.backgroundColor = _kBackgroundColor,
    this.foregroundColor,
    this.autoClose = _kAutoClose,
    this.borderRadius = BorderRadius.zero,
    this.padding,
    required this.onPressed,
    required this.child,
  }) : assert(flex > 0);

  /// {@template slidable.actions.flex}
  /// The flex factor to use for this child.
  ///
  /// The amount of space the child's can occupy in the main axis is
  /// determined by dividing the free space according to the flex factors of the
  /// other [MyCustomMySlidableAction]s.
  /// {@endtemplate}
  final int flex;

  /// {@template slidable.actions.backgroundColor}
  /// The background color of this action.
  ///
  /// Defaults to [Colors.white].
  /// {@endtemplate}
  final Color backgroundColor;

  /// {@template slidable.actions.foregroundColor}
  /// The foreground color of this action.
  ///
  /// Defaults to [Colors.black] if [background]'s brightness is
  /// [Brightness.light], or to [Colors.white] if [background]'s brightness is
  /// [Brightness.dark].
  /// {@endtemplate}
  final Color? foregroundColor;

  /// {@template slidable.actions.autoClose}
  /// Whether the enclosing [Slidable] will be closed after [onPressed]
  /// occurred.
  /// {@endtemplate}
  final bool autoClose;

  /// {@template slidable.actions.onPressed}
  /// Called when the action is tapped or otherwise activated.
  ///
  /// If this callback is null, then the action will be disabled.
  /// {@endtemplate}
  final MySlidableActionCallback? onPressed;

  /// {@template slidable.actions.borderRadius}
  /// The borderRadius of this action
  ///
  /// Defaults to [BorderRadius.zero].
  /// {@endtemplate}
  final BorderRadius borderRadius;

  /// {@template slidable.actions.padding}
  /// The padding of the OutlinedButton
  /// {@endtemplate}
  final EdgeInsets? padding;

  /// Typically the action's icon or label.
  final Widget child;

  @override
  Widget build(BuildContext context) {
    return Expanded(
        flex: flex,
        child: SizedBox.expand(
            child: MyTapWidget(
                onTap: () => _handleTap(context),
                child: Container(
                    decoration: BoxDecoration(
                        color: MyColours.colorE33432,
                        //设置四周圆角 角度
                        borderRadius: borderRadius),
                    alignment: Alignment.center,
                    child: child))));
  }

  void _handleTap(BuildContext context) {
    onPressed?.call(context);
    if (autoClose) {
      Slidable.of(context)?.close();
    }
  }
}
